// 由于最新的ora包只能用import的方式引入所以这里用了异步函数
(async function () {
    const { default: ora } = await import("ora");
    const scpClient = require("scp2");
    const path = require("path");
    const fs = require("fs");
    console.time('myFunction');
    const server = { 
        host: "8.222.239.137", // 目标服务器或主机IP
        port: 22, //目标服务器或主机端口 一般默认22 看情况
        username: "root", //ssh登录用户名
        password: "jian.141516", //ssh登录密码
        path: "/www/wwwroot/plat.ptpkx.com/dist", //目标服务器或主机目录
        // debug: console.log // 可以打印scp2的日志 方便调试
    };
    const distDirectory = "./dist/"; // 本地要上传的文件所在文件夹
    const checkFiles = []; // 这里因为我想当localdir中只包含"xxx.txt", "xxx.js"的时候才执行上传 如果不想校验数组设置为空数组
    const loadingColors = [
        "black",
        "red",
        "green",
        "yellow",
        "blue",
        "magenta",
        "cyan",
        "white",
        "gray",
    ];
    /**
     * 当前路径是否为目录
     * @param path 
     * @returns 
     */
    function isDirectory(path) {
        return fs.statSync(path).isDirectory();
    }
    /**
     * 校验localdir是否符合要求
     * @returns 
     */
    function checkDist() {
        const distPath = path.resolve(__dirname, distDirectory);
        if (!isDirectory(distPath)) {
            return false;
        }
        const files = fs.readdirSync(distPath);
        console.log("\r该目录文件:", files);
        console.log("校验文件:", checkFiles);
        if (!checkFiles.length) {
            return true;
        }
        if (files.length !== checkFiles.length) {
            return false;
        }
        return files.every((file) => checkFiles.includes(file));
    }
    let loading = ora("正在校验文件...");
    loading.start();
    const checkResult = checkDist();
    loading.stop();
    console.log(checkResult ? "文件校验通过" : "文件校验失败");
    if (!checkResult) {
        process.exit();
    }
    loading = ora("正在部署至 " + server.host);
    let counter = 0;
    setInterval(() => {
        counter++;
        loading.color = loadingColors[Date.now() % loadingColors.length];
    }, 1000);
    loading.start();
    scpClient.scp(distDirectory, server, (err) => {
        loading.stop();
        if (err) {
            console.log("部署失败");
            console.timeEnd('myFunction');
            throw err;
        } else {
            console.log("部署成功");
            console.timeEnd('myFunction');
            process.exit();
        }
    });
})();